package com.example.demo.util;

import lombok.SneakyThrows;
import lombok.extern.java.Log;
import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.*;
import java.nio.charset.StandardCharsets;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.example.demo.util;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2021/7/20 18:05]
 * @copyright: 2021 echovin.com
 */
@Log
public class MsgMqUtil {
    private static final int minPriority = 0;
    private static final int maxPriority = 9;
    private JmsMessagingTemplate jmsMessagingTemplate;
    private int acknowledge;
    private int deliveryMode;
    private int priority;
    private long timeToLive;

    /**
     *
     * @param jmsMessagingTemplate
     * @param acknowledge
     */
    public MsgMqUtil(JmsMessagingTemplate jmsMessagingTemplate, int acknowledge) {
        this.jmsMessagingTemplate = jmsMessagingTemplate;
        this.acknowledge = acknowledge;
    }

    /**
     *
     * @param jmsMessagingTemplate
     * @param acknowledge
     * @param deliveryMode
     * @param priority
     * @param timeToLive
     */
    public MsgMqUtil(JmsMessagingTemplate jmsMessagingTemplate, int acknowledge, int deliveryMode, int priority, long timeToLive) {
        this.jmsMessagingTemplate = jmsMessagingTemplate;
        this.acknowledge = acknowledge;
        this.deliveryMode = deliveryMode;
        this.priority = priority;
        this.timeToLive = timeToLive;
    }

    public boolean sendTopics(String topicName, String message) throws JMSException {
        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        Connection connection = null;
        boolean result = false;
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            Session session = connection.createSession(this.acknowledge);
            Destination destination = null;
            if (topicName.startsWith("topic://")){
                destination = new ActiveMQTopic(topicName.substring("topic://".length()));
            }else if (topicName.startsWith("queue://")){
                destination = new ActiveMQTopic(topicName.substring("queue://".length()));
            }else{
                destination = new ActiveMQTopic(topicName);
            }
            MessageProducer producer = session.createProducer(destination);
            sendMessage(message, session, producer);
            result = true;
        } catch (JMSException e) {
            log.warning(">>>>>>>>消息发送异常："+e.getMessage());
        }finally {
            if (connection != null){
                connection.close();
            }
        }
        return result;
    }

    private void sendMessage(String message, Session session, MessageProducer producer) throws JMSException {
        producer.setDeliveryMode(this.deliveryMode);
        if (this.priority < minPriority || this.priority > maxPriority){
            producer.setPriority(4);
        }else {
            producer.setPriority(this.priority);
        }
        producer.setTimeToLive(this.timeToLive);
        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(message.getBytes(StandardCharsets.UTF_8));
        producer.send(bytesMessage);
    }

    public String reviceMessage(Destination destination) throws JMSException {
        Connection connection = null;
        String[] result = {null};
        try {
            ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();
            Session session = connection.createSession(this.acknowledge);
            MessageConsumer consumer = session.createConsumer(destination);
            consumer.setMessageListener(new MessageListener() {
                @SneakyThrows
                @Override
                public void onMessage(Message message) {
                    String body = message.getBody(String.class);
                    result[0] = body;
                }
            });
        } catch (JMSException e) {
            log.warning(">>>>>>>>消息接收异常："+e.getMessage());
        } finally {
            if (connection != null){
                connection.close();
            }
        }
        return result[0];
    }
}
